package com.liruo.treasureattic.service.api.util;

import com.liruo.treasureattic.common.httpmsg.exception.ApiException;
import com.liruo.treasureattic.common.httpmsg.result.BaseResponse;
import com.liruo.treasureattic.common.httpmsg.result.Errno;

import java.util.function.Consumer;


/**
 * @Author:liruo
 * @Date:2022-11-10-19:20:54
 * @Desc
 */
public class ResultOpt<T> {
    private final BaseResponse<T> resp;

    public ResultOpt(BaseResponse<T> resp) {
        this.resp = resp;
    }

    public static <R> ResultOpt<R> opt(BaseResponse<R> resp){
        return new ResultOpt<>(resp);
    }

    public T data(Consumer<T> errHandler){
        if(resp.getCode() != Errno.SUCCESS.getCode()){
            errHandler.accept(resp.getData());
        }
        return resp.getData();
    }

    /**
     * @param beforeMsg api method info
     * @return
     */
    public T data(String beforeMsg){
        if(resp.getCode() != Errno.SUCCESS.getCode()){
            throw new ApiException(Errno.INNER_API, "api info[" + beforeMsg + "]," + "err = " + resp.getData());
        }
        return resp.getData();
    }
}
